/**
 * 
 * const {commitLintConfig} = require("flexci")
 * module.exports = commitLintConfig({
 *      // 重载覆盖
 * })
 * 
 * 
 */
import { deepMerge } from "flex-tools/object"
import type {UserConfig} from '@commitlint/types';
import { asyncExecShellScript, installPackage, execProjectShellCommand } from "../../utils";
import logsets from 'logsets';
import { FlexCiFeatureDefinition } from "../../types";
import fs from "fs-extra" 


const commitlintConfig =`const { commitlint } = require("flexci")
module.exports = commitlint.config({
    // 在此重载commitlint配置,可用配置项详见https://commitlint.js.org/#/reference-configuration
    //rules: { 
    //    "scope-enum":[1,"always",[
    //    此处列出当前项目可选的模块或scope,这样当执行pnpm commit时会让您进行选择而不用手动输入
    ]]
    // 例如："scope-enum":[1,"always",["core","banner","progressbar","tree","table","tasklist"]]
    //},
}`


/**
 * 启用commitlint功能
 */

export interface CommitlintFeatureOptions{

}

 export const commitlint:FlexCiFeatureDefinition<CommitlintFeatureOptions> = {
    title:"提交信息规范(commitlint)",
    install:async (options,selectedFeatures)=>{
        
        const tasks = logsets.tasklist()
        await tasks.run("安装{}",["husky"],async () => {
            await installPackage("husky",{type:"dev"});
            await execProjectShellCommand(`husky install`)
            await asyncExecShellScript(`npm pkg set script.prepare="husky install"`)
        })    
        await tasks.run("安装<{}>Git钩子",["commit-msg"],async () => {
            await asyncExecShellScript(`npx husky add .husky/commit-msg "commitlint --edit "\${1}""`)
        })    

        await tasks.run("安装{}",["@commitlint/config-conventional"],async () => {
            return await installPackage("@commitlint/config-conventional",{type:"dev"});
        })  
        
        await tasks.run("安装{}",["@commitlint/cli"],async () => {
            return await installPackage("@commitlint/cli",{type:"dev"});
        })    

        await tasks.run("安装{}",["@commitlint/cz-commitlint"],async () => {
            return await installPackage("@commitlint/cz-commitlint",{type:"dev"});
        })    

        await tasks.run("安装{}",["conventional-changelog-cli"],async () => {
            return await installPackage("conventional-changelog-cli",{type:"dev"});
        })  
        await tasks.run("安装{}",[" "],async () => {
            await installPackage("commitizen",{type:"dev"});
            await asyncExecShellScript("npm pkg set config.commitizen.path=@commitlint/cz-commitlint")
        })   
        await tasks.run("创建配置文件{}",["commitlint.config"],async () => {
            if(fs.existsSync("commitlint.config.js")){
                return "skip"
            }else{
                await fs.writeFile("commitlint.config.js",commitlintConfig)            
            }
        })
        await tasks.run("配置{}命令",["commit"],async () => {
            await asyncExecShellScript(`npm pkg set scripts.commit="git add . && git-cz"`)
        }) 
        // 如果没有启用docs则将changelog生成在项目根目录
        if(!("docs" in selectedFeatures)){
            await tasks.run("配置{}命令",["changelog"],async () => {
                await asyncExecShellScript(`npm pkg set scripts.version="npm changelog"`)
                await asyncExecShellScript(`npm pkg set scripts.changelog="conventional-changelog -p angular -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md"`)                
            })  
        }
    },
    config:function(config:UserConfig):UserConfig {    
        return deepMerge({
            extends: ["@commitlint/config-conventional"],
            defaultIgnores: false,
            rules: {
                //enableMultipleScopes:true,
                //"scope-enum": [1, "always", ["core", "file-backend", "http-backend", "console-backend", "syslog-backend"]]
            },
            prompt: {
                settings: {
                    enableMultipleScopes: true,
                    scopeEnumSeparator: ","
                },
                messages: {
                    skip: "跳过",
                    max: "最大支持%d个字符",
                    min: "不能少于%d个字符",
                    emptyWarning: "不能为空",
                    upperLimitWarning: "超过了字符限制",
                    lowerLimitWarning: "字符数小于下限",
                },
                questions: {
                    type: {
                        description: "选择你要提交的类型:",
                        enum: {
                            feat: {
                                title: "特性",
                                description: "   🚀  新增功能",
                                emoji: "🚀",
                            },
                            fix: {
                                title: "修复",
                                description: "   🐛  修复缺陷",
                                emoji: "🐛",
                            },
                            docs: {
                                title: "文档",
                                description: "   📚  文档变更",
                                emoji: "📚",
                            },
                            style: {
                                title: "格式",
                                description: "   🎨  代码格式(不影响功能，例如空格、分号等格式修正)",
                                emoji: "🎨",
                            },
                            refactor: {
                                title: "重构",
                                description: "   🛠   代码重构(不包括 bug 修复、功能新增)",
                                emoji: "🛠",
                            },
                            perf: {
                                title: "性能",
                                description: "   ⚡️  性能优化",
                                emoji: "⚡️",
                            },
                            test: {
                                title: "测试",
                                description: "   ✅  添加测试或已有测试改动",
                                emoji: "✅",
                            },
                            build: {
                                title: "构建",
                                description:
                                    "   📦  构建流程、外部依赖变更(如升级 npm 包、修改 webpack 配置等)",
                                emoji: "📦",
                            },
                            ci: {
                                title: "集成",
                                description: "   🎡  修改 CI 配置、脚本",
                                emoji: "🎡",
                            },
                            chore: {
                                description: "   ♻️   除源代码文件和测试文件之外的改变",
                                title: 'Chores',
                                emoji: '♻️',
                            },
                            revert: {
                                title: "回退",
                                description: "   ⏪️  回滚 commit",
                                emoji: "⏪️",
                            },
                            other: {
                                title: "其他",
                                description: "   🔨  对构建过程或辅助工具和库的更改(不影响源文件、测试用例)",
                                emoji: "🔨",
                            },
                        },
                    },
                    scope: {
                        description: "本次提交涉及的模块或范围(可选):",
                    },
                    subject: {
                        description: "填写简短精炼的变更描述 :\n",
                    },
                    body: {
                        description:
                            '填写更加详细的变更描述(可选)。使用 "|" 换行 :\n',
                    },
                    breaking: {
                        description:
                            '列举非兼容性重大的变更(可选)。使用 "|" 换行 :\n',
                    },
                    isBreaking: {
                        description: '本次提交是一个不兼容的变更?',             // Are there any breaking changes?
                    }, 
                    isIssueAffected: {
                        description: "是否会影响任何未解决的issue问题?"
                    },
                    issues: {
                        description: "列举关联issue (可选) 例如: #31, #I3244 :\n",
                    },
                },
            }
        }, config)
    }    
}  

